package framework.ui;


import org.openems.entity.Entity;
import org.openems.entity.Key;
import javafx.scene.input.KeyCode;
import framework.DomainService;
import framework.EntityStoreListener;

public class EmsEditConnector {

	private DomainService store;
	private ITextField textField;
	
	private EntityStoreListener entityStoreListener = new EntityStoreListener() {
		@Override
		public void valueChanged(Entity entity) {
			textField.setText(entity.getValueText());
		}
	};
	

	public EmsEditConnector(ILabel title, final ITextField textField, final DomainService service,
			final Key key) {
		this.store = service;
		this.textField = textField;
		
		final Entity entity = service.getEntity(key);
		title.setText(entity.getName());
		textField.setText(entity.getValueText());
		textField.setOnKeyPressed(new ITextFieldListener() {
			@Override
			public void keyPressed(KeyCode arg0) {
				if (arg0 == KeyCode.ENTER && ! textField.getText().isEmpty()) {
					try {
						entity.setValueText(textField.getText());
						service.putEntity(entity);
					}
					catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		
		service.addEntityStoreListener(entityStoreListener, key);
	}

	public void remove() {
		store.removeEntityStoreListener(entityStoreListener);
	}
}
